//
//  MerchandiseEditController.m
//  ios-supplier
//
//  Created by feynmanyuan on 15/4/21.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import "MerchandiseEditController.h"

@interface MerchandiseEditController ()<UIGestureRecognizerDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIButton *swShelfBtn;
@property (weak, nonatomic) IBOutlet UILabel *marketPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;

@property (weak, nonatomic) IBOutlet UIButton *saveBtn;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *unitLabel;
@property (weak, nonatomic) IBOutlet UILabel *weightLabel;
- (IBAction)saveAction:(id)sender;
- (IBAction)swAction:(id)sender;
@property (weak, nonatomic) IBOutlet UILabel *shelfStatusLabel;

@property (weak, nonatomic) IBOutlet UISwitch *shelfSwitch;

@property (weak, nonatomic) IBOutlet UITextField *modifyPriceTextLabel;
@property (weak, nonatomic) IBOutlet UITextField *addStockTextLabel;//修改库存
@property (weak, nonatomic) IBOutlet UILabel *currentStockLabel;
@property (weak, nonatomic) IBOutlet UIView *marketPriceView;
@property (weak, nonatomic) IBOutlet UIView *goodsPriceView;


@property (weak, nonatomic) IBOutlet UIView *shelfView;
@property (weak, nonatomic) IBOutlet UIView *modifyView;
@property (weak, nonatomic) IBOutlet UIView *addStockView;
@property (weak, nonatomic) IBOutlet UIView *currentStockView;
@property (weak, nonatomic) IBOutlet UILabel *addStockLabel;
//@property (nonatomic, strong) UIButton *subBtn;
@property (weak, nonatomic) IBOutlet UILabel *shangJiaLabel;//上下架显示
@property (weak, nonatomic) IBOutlet UIView *changePriceView;//门店价
@property (weak, nonatomic) IBOutlet UIButton *changeDelButton;
@property (weak, nonatomic) IBOutlet UIButton *changeAddButton;
@property (nonatomic, assign)int labelNumber;

@end

@implementation MerchandiseEditController

- (void)viewDidLoad {
    [super viewDidLoad];
    //改变门店价的样式
    self.changePriceView.layer.borderWidth = 1.0f;
    self.changePriceView.layer.borderColor = [[UIColor grayColor]CGColor];
    self.changePriceView.layer.cornerRadius = 4.0f;
    //给加减一个点击事件
    [self.changeDelButton addTarget:self action:@selector(delChangeBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.changeAddButton addTarget:self action:@selector(addChangeBtn) forControlEvents:UIControlEventTouchUpInside];
    if (_merchandise.saleType == 3) // 非移动商户隐藏上下架 和 修改商品价格的修改行
    {
        self.shelfView.hidden = YES;
        self.modifyView.hidden = YES;
        self.addStockLabel.text = @"减少库存量";
        [self.addStockTextLabel setKeyboardType: UIKeyboardTypeNumberPad];
        //  self.changeAddButton.userInteractionEnabled = NO;
        //self.changeAddButton.enabled = NO;
        [self.changeAddButton removeTarget:self action:@selector(addChangeBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.changeAddButton addTarget:self action:@selector(addChangeBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        [self reSetFrame];
    }
    else
    {
        self.shelfView.hidden = NO;
        self.modifyView.hidden = NO;
        [self.addStockTextLabel setKeyboardType: UIKeyboardTypeNumbersAndPunctuation];
    }
    
    self.modifyPriceTextLabel.text = [NSString stringWithFormat:@"%@", [NSString decimalToString:_merchandise.storePrice]];
    [self.modifyPriceTextLabel setKeyboardType: UIKeyboardTypeDecimalPad];
    self.shelfSwitch.on = _merchandise.mpStatus == 4 ? YES : NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHidden) name:UIKeyboardDidHideNotification object:nil];
    
    [self.swShelfBtn setImage:[UIImage imageNamed:@"sw_close"] forState:UIControlStateNormal];
    [self.swShelfBtn setImage:[UIImage imageNamed:@"sw_open"] forState:UIControlStateSelected];
    [self.saveBtn setBackgroundColor:TextColorImportButton];
    
    self.marketPriceLabel.text = [NSString stringWithFormat:@"¥ %@", [NSString decimalToString:_merchandise.marketPrice]];
    self.priceLabel.text = [NSString stringWithFormat:@"¥ %@", [NSString decimalToString:_merchandise.storePrice]];
    [self.swShelfBtn setSelected:_merchandise.mpStatus];
    NSLog(@"http://wup.jufangbian.com/upload/product_image/product_200/%lu.jpg", (unsigned long)_merchandise.mpId);
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", _merchandise.mpURL]] placeholderImage:[UIImage imageNamed:ImageDefaultPlaceholder]];
    self.nameLabel.text = _merchandise.name;
    self.unitLabel.text = [NSString stringWithFormat:@"单位：%@/%@丨重量：%@", _merchandise.calculationUnit,_merchandise.standard,_merchandise.standard];
    self.currentStockLabel.text = [NSString stringWithFormat: @"%ld", (long)_merchandise.stockNum];
    //改变的库存第一次进来显示的是默认库存量
    self.addStockTextLabel.text = [NSString stringWithFormat:@"%ld",(long)_merchandise.stockNum];
    self.modifyPriceTextLabel.delegate = self;
    self.addStockTextLabel.delegate = self;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self.navigationItem setLeftBarButtonItem: [self createBackView]];
}
#pragma mark -点击减号
-(void)delChangeBtn{
    
    
    if ([self.addStockTextLabel.text  integerValue] > 0) {
        self.addStockTextLabel.text = [NSString stringWithFormat:@"%ld",[self.addStockTextLabel.text integerValue]-1];
    }
    
    
    
}
-(void)addChangeBtn:(NSInteger) saleType{
    
    [JFBUIAnimation alertTips:@"不能增加精选商品的库存量"];
    return;
    
    
}
-(void)addChangeBtn{
    
    self.labelNumber++;
    self.addStockTextLabel.text = self.addStockTextLabel.text = [NSString stringWithFormat:@"%ld",[self.addStockTextLabel.text integerValue]+1];
}
-(void)keyboardDidHidden
{
    //设置view的frame，往下平移
    [self.saveBtn setFrame:CGRectMake(0, self.view.frame.size.height - 60, self.view.bounds.size.width, 60)];
}



- (UIBarButtonItem *)createBackView
{
    UIButton *leftButtonItem = [UIButton buttonWithType:UIButtonTypeCustom];
    
    leftButtonItem.frame = CGRectMake(0, 0, 11, 20);
    
    [leftButtonItem setBackgroundImage:[UIImage imageNamed:@"icon-Back"] forState:UIControlStateNormal];
    
    [leftButtonItem setImageEdgeInsets: UIEdgeInsetsMake((19 - 11) / 2, 0, (19 - 11) / 2, 0)];
    
    [leftButtonItem addTarget:self action:@selector(leftButtonItemClicked) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:leftButtonItem];
    
    return item;
}

-(void)leftButtonItemClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)reSetFrame
{
    CGFloat maxY = CGRectGetMaxY(self.weightLabel.frame);
    CGFloat height = self.marketPriceView.frame.size.height;
    CGFloat centerY = height / 2 + maxY + 15;
    
    self.marketPriceView.center = CGPointMake(self.marketPriceView.center.x, centerY);
    self.goodsPriceView.center = CGPointMake(self.goodsPriceView.center.x, self.marketPriceView.center.y + height);
    self.currentStockView.center = CGPointMake(self.currentStockView.center.x, self.goodsPriceView.center.y + height + 15);
    self.addStockView.center = CGPointMake(self.addStockView.center.x, self.currentStockView.center.y + height);
}

- (IBAction)saveAction:(id)sender {
    
    if (self.addStockTextLabel.text.length == 0) {
        [JFBUIAnimation alertTips: @"不能为空"];
        return;
    }
    
    NSDecimalNumber *price = [NSString formatDecimal:_merchandise.marketPrice];
    NSDecimalNumber *modifyPrice = [[NSDecimalNumber alloc]initWithString:self.modifyPriceTextLabel.text];
    NSString *text= self.priceLabel.text;
    
    NSRange range = [text rangeOfString:@"¥ "];
    
    
    NSDecimalNumber *storePrice = [[NSDecimalNumber alloc]initWithString:[text substringFromIndex:range.length]];
    NSDecimalNumber *add_inventory_qty = [[NSDecimalNumber alloc]initWithString:self.addStockTextLabel.text];
    
    if (modifyPrice.doubleValue == storePrice.doubleValue &&[add_inventory_qty intValue]==[self.currentStockLabel.text intValue]) {
        [JFBUIAnimation alertTips: @"修改成功"];
        [self.delegate reload];
        [self.navigationController popViewControllerAnimated:YES];
        return;
        
    }
    
    if (_merchandise.saleType != 3 )
    {
        NSMutableString *modifyString =  [NSMutableString stringWithString: self.modifyPriceTextLabel.text];
        NSRange pointRange = [modifyString rangeOfString: @"."];
        if ((pointRange.length > 0 && [modifyString substringFromIndex: pointRange.location + 1].length > 1) || modifyString.length == 0 ) {
            [JFBUIAnimation alertTips: @"价格只能保留一位小数"];
            return;
        }
        if (modifyPrice.doubleValue > price.doubleValue * 1.5 || modifyPrice.doubleValue < price.doubleValue * 0.5) {
            [JFBUIAnimation alertTips: @"价格浮动不能超过50%"];
            return;
        }
        if (modifyPrice.doubleValue < 0) {
            [JFBUIAnimation alertTips: @"价格不能为负值"];
            return;
        }
    }
    //    else
    //    {
    //         add_inventory_qty = [[NSDecimalNumber alloc]initWithLong: add_inventory_qty.integerValue * -1] ;
    //    }
    
    
    if (([add_inventory_qty intValue] + [self.currentStockLabel.text intValue]) < 0) {
        [JFBUIAnimation alertTips: @"库存量不能为负值"];
        return;
    }
    
    //NSInteger mpStatus = self.shelfSwitch.on == YES ? 4 : -1;
    
    NSInteger newStatus = self.shelfSwitch.on?4:5;
    
    if(_merchandise.saleType == 3){
        newStatus = _merchandise.mpStatus;
    }
    [JFBMerchandiseDS changeUnitPrice:^(BOOL isSuccess, NSString *message, NSError *error) {
        [JFBUIAnimation alertTips:message];
        [self.delegate reload];
        [self.navigationController popViewControllerAnimated:YES];
        
    } mpId:_merchandise.mpId realStockNum:[self.currentStockLabel.text integerValue] addstockNum:add_inventory_qty storePrice:modifyPrice oldStatus:_merchandise.mpStatus newStatus:newStatus  saleType:_merchandise.saleType];
    
}
#pragma mark -点击上下架的时候调用接口
- (IBAction)swAction:(id)sender {
    
    
    [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeBlack];
    [JFBMerchandiseDS switchUpAndDownShelf:^(BOOL isSuccess, NSError *error) {
        [SVProgressHUD dismiss];
        if( isSuccess ) {
            //            _merchandise.mpStatus = !_merchandise.mpStatus;
            //            self.shangJiaLabel.text = _merchandise.mpStatus ? @"已上架" : @"已下架";
            //            [self.swShelfBtn setSelected:_merchandise.mpStatus];
            [JFBUIAnimation alertTips:@"上下架状态修改成功"];
            //[self.delegate reload];
        }
    } merchandiseID:_merchandise.mpId oldStatus:_merchandise.mpStatus newStatus: self.shelfSwitch.on? 4 : 5 saleType:_merchandise.saleType];
}


// 输入框弹出键盘时自动上移
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == self.addStockTextLabel) {
        self.addStockTextLabel.text = @"";
    }
    
    CGRect addStockRect = [self.addStockTextLabel convertRect: self.addStockTextLabel.frame toView: self.view];
    CGFloat offSet = self.view.frame.size.height - (CGRectGetMaxY(addStockRect) + 216 + 40);
    
    if (offSet < 0) {
        [UIView animateWithDuration: 0.25 animations:^{
            CGRect frame = self.view.frame;
            frame.origin.y = offSet;
            self.view.frame = frame;
        }];
    }
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [UIView animateWithDuration: 0.25 animations:^{
        CGRect frame = self.view.frame;
        frame.origin.y = 0;
        self.view.frame = frame;
    }];
    
    if (textField == self.addStockTextLabel) {
        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
        [numberFormatter setNumberStyle: NSNumberFormatterNoStyle];
        NSNumber *num = [numberFormatter numberFromString: self.addStockTextLabel.text];
        NSLog(@"%@",num);
        
        if (num == nil) {
            self.addStockTextLabel.text = @"0";
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入整数" delegate: nil cancelButtonTitle: @"确定" otherButtonTitles: nil];
            [alert show];
        }
    }
}

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    return YES;
}

- (BOOL)endEditing:(BOOL)force
{
    return YES;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.modifyPriceTextLabel resignFirstResponder];
    [self.addStockTextLabel resignFirstResponder];
}



@end
